/* ********************************************************************************* 
*    Copyright:  (C) 2023 LN
*    All rights reserved.
*
*       Filename:  ds18b20.c
*    Description:  This file 
*                 
*      Version:  1.0.0(2023年04月05日)
*       Author:  Li Haipeng <NULL>
*    ChangeLog:  1, Release initial version on "2023年04月05日 23时11分23秒"
*
***********************************************************************************/
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

int get_temp(float *temp)
{
    int	             fd = -1;
    int	             found = 0;
    char             buf[128];
    char             path[32] = "/sys/bus/w1/devices/";
    char             t_path[16];
    char             w_path[64];
    char            *ptr = NULL;
    DIR	            *dirp = NULL ;
    struct dirent	*direntdirp = NULL ;

    dirp = opendir(path);

    if( !dirp )
    {
        printf("dirp errno:%s\n", strerror(errno));
        return -1;
    }

    while( (direntdirp = readdir(dirp)) )
    {
        if( strstr(direntdirp->d_name, "28-") )
        {
            strncpy(t_path, direntdirp->d_name, sizeof(t_path));
         	found = 1;
        }
    }

    closedir(dirp);

    if( !found )
    {
        printf("t_path errno:%s\n", strerror(errno));
        return -2;
    }

    snprintf(w_path, sizeof(w_path), "%s/%s/w1_slave", path, t_path);
    if(NULL == w_path)
    {
        printf("w_path errno:%s\n", w_path);
        return -3;
    }
	
    fd = open(w_path, O_RDONLY);
    memset(buf, 0, sizeof(buf));
    read(fd, buf, sizeof(buf));

    close(fd);
	
    ptr = strstr(buf, "t=");
    if( !ptr )
    {
        printf("ptr errno:%s\n", strerror(errno));
        return -4;
    }
    ptr += 2;
    *temp = atof(ptr)/1000;
	
    return 0;
}
